package com.yanqu.road.server.manger.player;

import com.yanqu.road.entity.activity.ActivityDisperseGoldInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.winterLove.config.WinterLoveConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.bussiness.player.UserActivityDisperseGoldBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.ActivityDisperseGoldPb;
import com.yanqu.road.pb.activity.ActivityDisperseGoldProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.HolidayActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.treasure.TreasureActivityMgr;
import com.yanqu.road.server.manger.activity.winterLove.WinterLoveMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.*;

/**
 * 活动散财
 */
public class ActivityDisperseGoldMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(ActivityDisperseGoldMgr.class);

    private static Map<Long, ActivityDisperseGoldInfo> disperseGoldMap;

    public static void addActivityDisperseGoldInfo(ActivityDisperseGoldInfo goldInfo) {
        synchronized (disperseGoldMap) {
            if (disperseGoldMap.get(goldInfo.getDisperseId()) == null) {
                goldInfo.setInsertOption();
                disperseGoldMap.put(goldInfo.getDisperseId(), goldInfo);
            }
        }
    }

    @Override
    public boolean reloadData() {
        disperseGoldMap = UserActivityDisperseGoldBussiness.getDisperseGoldMap();
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        Iterator<ActivityDisperseGoldInfo> iterator = disperseGoldMap.values().iterator();
        while (iterator.hasNext()) {
            ActivityDisperseGoldInfo info = iterator.next();
            if(info.isInsertOption()){
                UserActivityDisperseGoldBussiness.addDisperseGold(info);
            }else if(info.isUpdateOption()){
                UserActivityDisperseGoldBussiness.updateDisperseGold(info);
            }
        }
        return true;
    }

    /**
     * 汇总本服领奖情况
     * @param goldInfo
     * @param property
     */
    public static void summaryReward(ActivityDisperseGoldInfo goldInfo, Property property){
        synchronized (goldInfo){
            Property oldProperty = PropertyHelper.parseStringToProperty(goldInfo.getReward());
            if(oldProperty == null){
                oldProperty = new Property();
            }
            oldProperty.addProperty(property);
            goldInfo.setReward(PropertyHelper.parsePropertyToString(oldProperty));
            goldInfo.setPlayerNum(goldInfo.getPlayerNum() + 1);
        }
    }


    /**
     * 获取送财信息
     * @param disperseId
     * @return
     */
    public static ActivityDisperseGoldInfo getDisperseGoldInfo(long disperseId) {
        return disperseGoldMap.get(disperseId);
    }

    /**
     * 获取时限内的散财记录
     * @return
     */
    public static List<ActivityDisperseGoldInfo> needSendDisperseGold() {
        if (disperseGoldMap.size() == 0) {
            return null;
        }
        List<ActivityDisperseGoldInfo> list = new ArrayList<>();
        for(ActivityDisperseGoldInfo goldInfo : disperseGoldMap.values()){
            if(goldInfo.isSendEmail()){
                continue;
            }
            if(isDisperseGoldEnd(goldInfo)){
                continue;
            }
            list.add(goldInfo);
        }
        //升序，确保有序
        list.sort(new Comparator<ActivityDisperseGoldInfo>() {
            @Override
            public int compare(ActivityDisperseGoldInfo o1, ActivityDisperseGoldInfo o2) {
                if(o2.getDisperseId() > o1.getDisperseId()){
                    return -1;
                }
                if(o2.getDisperseId() < o1.getDisperseId()){
                    return 1;
                }
                return 0;
            }
        });
        return list;
    }

    /**
     * 发送邮件给送糖者，或者回执跨服送糖结果
     */
    public static void checkDisperseGoldResult() {
        if(disperseGoldMap == null || disperseGoldMap.size() == 0){
            return;
        }
        for(ActivityDisperseGoldInfo disperseGoldInfo : disperseGoldMap.values()){
            if(disperseGoldInfo.isSendEmail()){         //已邮件发奖
                continue;
            }
            if(!isDisperseGoldEnd(disperseGoldInfo)){  //
                continue;
            }
            if(disperseGoldInfo.getServerId() == GameServer.getInstance().getServerId()){
                //等待一次,确保跨服送财都结束了
                if (!disperseGoldInfo.isWait()){
                    disperseGoldInfo.setWait(true);
                    pushResultToCrossServer(disperseGoldInfo, false);
                    continue;
                }
                //到跨服取数据（跨服推送汇总数据给区服）
                pushResultToCrossServer(disperseGoldInfo, true);
                //sendMailToGoldOwner(disperseGoldInfo);
            }else {
                disperseGoldInfo.setSendEmail(true);   //非本服直接标注已发邮件，避免重复推送结果
                pushResultToCrossServer(disperseGoldInfo, false);
            }
        }
        removeOutTimeData();
    }

    public static void removeOutTimeData(){
        long curMillSeconds = System.currentTimeMillis();
        Set<Long> keys = disperseGoldMap.keySet();
        for(long key : keys){
            ActivityDisperseGoldInfo goldInfo = disperseGoldMap.get(key);
            if (curMillSeconds - goldInfo.getBeginTime() > 24 * 60 * 60 * 1000) {
                if(!goldInfo.isDirty() && goldInfo.isSendEmail()){
                    synchronized (disperseGoldMap){
                        disperseGoldMap.remove(key);
                    }
                }
            }
        }
    }

    private static void pushResultToCrossServer(ActivityDisperseGoldInfo disperseGoldInfo, boolean canMail) {
        //推送跨服送糖结果
        ActivityDisperseGoldProto.ActivityDisperseGoldInfoTemp.Builder goldInfoTemp = ActivityDisperseGoldPb.parseToDisperseGoldInfoTemp(disperseGoldInfo);
        goldInfoTemp.setCanMail(canMail);
        YanQuMessage pbMessage = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_ACTIVITY_DISPERSE_GOLD_RESULT_PUSH, goldInfoTemp);
        GamePlayerMgr.sendPacket(0, pbMessage);
    }

    /**
     * 发送邮件给散财者
     * @param crossGoldInfo
     */
    public static void sendMailToGoldOwner(ActivityDisperseGoldInfo crossGoldInfo) {
        ActivityDisperseGoldInfo disperseGoldInfo = getDisperseGoldInfo(crossGoldInfo.getDisperseId());
        if(disperseGoldInfo == null){
            return;
        }
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId());
        if(activityInfo == null){
            return;
        }
        if(disperseGoldInfo.isSendEmail()){
            return;
        }
        disperseGoldInfo.setSendEmail(true);
        if(activityInfo.getType() == eActivityType.CrossHolidayActivity.getValue()){
            //发送邮件给发糖者
            UserInfo userInfo = UserMgr.getUserInfo(crossGoldInfo.getUserId());
            Property property = PropertyHelper.parseStringToProperty(crossGoldInfo.getReward());
            if (property == null) {
                property = new Property();
            }
            BigInteger silver = property.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER);
            List<Integer> param4List = HolidayActivityMgr.getActivityParam4(activityInfo);
            int candyGoodId = param4List.get(2);
            BigInteger candyNum = property.getCountByGoodsId(candyGoodId);

            String mailTitleKey = MailManager.ACTIVITY_DISPERSE_GOLD_REWARD_TITLE;
            String  mailContentKey = MailManager.ACTIVITY_DISPERSE_GOLD_REWARD_CONTENT;
            if(activityInfo.getChildType() != 1){
                mailTitleKey = MailManager.ACTIVITY_DISPERSE_GOLD_REWARD_TITLE + "_" + activityInfo.getChildType();
                mailContentKey = MailManager.ACTIVITY_DISPERSE_GOLD_REWARD_CONTENT + "_" + activityInfo.getChildType();
            }
            String mailTitle = MultipleLanguageMgr.getContent(mailTitleKey, userInfo.getLanguage());
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(mailContentKey, userInfo.getLanguage()), crossGoldInfo.getPlayerNum(), silver, candyNum);
            MailManager.sendMail(crossGoldInfo.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
        }else if(activityInfo.getType() == eActivityType.ThrowingPotActivity.getValue()){
            //发送邮件给活动散财的那个人
            UserInfo userInfo = UserMgr.getUserInfo(crossGoldInfo.getUserId());
            Property property = PropertyHelper.parseStringToProperty(crossGoldInfo.getReward());
            if (property == null) {
                property = new Property();
            }
            BigInteger silver = property.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER);
            int candyGoodId = eItemId.THROWING_POT_JIAN_DAI.getValue();
            BigInteger candyNum = property.getCountByGoodsId(candyGoodId);

            String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_DISPERSE_GOLD_THROWING_POT_REWARD_TITLE, userInfo.getLanguage());
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ACTIVITY_DISPERSE_GOLD_THROWING_POT_REWARD_CONTENT,
                    userInfo.getLanguage()), crossGoldInfo.getPlayerNum(), silver, candyNum);
            MailManager.sendMail(crossGoldInfo.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
        }else if(activityInfo.getType() == eActivityType.YearMasterActivity.getValue()){
            //发送邮件给活动散财的那个人
            UserInfo userInfo = UserMgr.getUserInfo(crossGoldInfo.getUserId());
            Property property = PropertyHelper.parseStringToProperty(crossGoldInfo.getReward());
            if (property == null) {
                property = new Property();
            }
            BigInteger silver = property.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER);
            //元宝id
            BigInteger ingots = property.getCountByGoodsId(GameConfig.GAME_MONEY_INGOTS);

            String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_DISPERSE_GOLD_YEAR_MASTER_REWARD_TITLE, userInfo.getLanguage());
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ACTIVITY_DISPERSE_GOLD_YEAR_MASTER_REWARD_CONTENT,
                    userInfo.getLanguage()), crossGoldInfo.getPlayerNum(), silver, ingots);
            MailManager.sendMail(crossGoldInfo.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);

        }else if(activityInfo.getType() == eActivityType.TreasureActivity.getValue()){
            //发送邮件
            UserInfo userInfo = UserMgr.getUserInfo(crossGoldInfo.getUserId());
            Property property = PropertyHelper.parseStringToProperty(crossGoldInfo.getReward());
            if (property == null) {
                property = new Property();
            }

            BigInteger silver = property.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER);

            int goldGoodId = TreasureActivityMgr.getActivityGoldRewardId(activityInfo);
            GoodsInfo goldInfo = GoodsMgr.getGoodsById(goldGoodId);
            BigInteger goldGoodNum = property.getCountByGoodsId(goldGoodId);

            //  {0}活动
            //   亲爱的掌柜，您在本次{0}中共有{1}名掌柜收到，送出银两数{2}、{3}{4}
            String  mailTitleKey = MailManager.ACTIVITY_DISPERSE_GOLD_TREASURE_REWARD_TITLE;
            String  mailContentKey = MailManager.ACTIVITY_DISPERSE_GOLD_TREASURE_REWARD_CONTENT;

            String activityName = ActivityMgr.getActivityName(activityInfo, userInfo.getLanguage());

            String mailTitle = StringUtils.format(MultipleLanguageMgr.getContent(mailTitleKey, userInfo.getLanguage()),activityName);
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(mailContentKey, userInfo.getLanguage()),activityName,crossGoldInfo.getPlayerNum(),silver,
                    ServerLanguageMgr.getContent(goldInfo.getGoodsName(),userInfo.getLanguage()),goldGoodNum);
            MailManager.sendMail(crossGoldInfo.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
        } else if (activityInfo.getType() == eActivityType.WinterLoveActivity.getValue()) {
            //发送邮件
            UserInfo userInfo = UserMgr.getUserInfo(crossGoldInfo.getUserId());
            Property property = PropertyHelper.parseStringToProperty(crossGoldInfo.getReward());
            if (property == null) {
                property = new Property();
            }
            BigInteger silver = property.getCountByGoodsId(GameConfig.GAME_MONEY_SILVER);




            WinterLoveConfig config = WinterLoveMgr.loadWinterLoveConfigFromDb(activityInfo);
            String titleKey = null;
            String contentKey = null;
            int sockId = eItemId.WINTER_LOVESONG_SOCK_ITEM_ID.getValue();
            if (config != null) {
                titleKey = config.getMAIL_TITLE_DISPERSE_GOLD();
                contentKey = config.getMAIL_CONTENT_DISPERSE_GOLD();
                sockId = config.getDisperseGoldSock();
            }
            BigInteger sockGoodNum = property.getCountByGoodsId(sockId);
            boolean useServerLanguage = true;
            if (StringUtils.isNullOrEmpty(titleKey)) {
                useServerLanguage = false;
                titleKey = MailManager.ACTIVITY_DISPERSE_GOLD_WINTER_LOVE_REWARD_TITLE;
            }

            if (StringUtils.isNullOrEmpty(contentKey)) {
                 contentKey = MailManager.ACTIVITY_DISPERSE_GOLD_WINTER_LOVE_REWARD_CONTENT;          //亲爱的掌柜，在本次冬季恋歌活动中有{0}名掌柜收到您的圣诞送礼，共送出银两×{1}、圣诞袜×{2}。

            }
            if (useServerLanguage) {
                String language = userInfo.getLanguage();
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(sockId);

                String mailTitle = StringUtils.format( ServerLanguageMgr.getContent(titleKey,language ),ActivityMgr.getActivityName(activityInfo,language));
                String mailContent = StringUtils.format(ServerLanguageMgr.getContent(contentKey, userInfo.getLanguage()),ActivityMgr.getActivityName(activityInfo,language), crossGoldInfo.getPlayerNum(), silver,ServerLanguageMgr.getContent(goodsInfo.getGoodsName(),language) ,sockGoodNum);
                MailManager.sendMail(crossGoldInfo.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
            }else {
                String mailTitle = MultipleLanguageMgr.getContent(titleKey, userInfo.getLanguage());
                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(contentKey, userInfo.getLanguage()), crossGoldInfo.getPlayerNum(), silver, sockGoodNum);
                MailManager.sendMail(crossGoldInfo.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
            }
        } else {

        }
    }


    /**
     * 是否在送糖的有效期限内
     * @param disperseGoldInfo
     * @return
     */
    public static boolean isDisperseGoldEnd(ActivityDisperseGoldInfo disperseGoldInfo) {
        String honoraryTitles = disperseGoldInfo.getHonoraryTitles();
        int honoraryNum = honoraryTitles.split(",").length;
        if(honoraryNum == 0){
            honoraryNum = 1;
        }
        // 距离开始送财时间间隔
        long time = (System.currentTimeMillis() - disperseGoldInfo.getBeginTime()) / 1000;
        // 时间限制=送财时间限制+播放动画初始时间+播放动画增长时间*称号个数
        int duration = GameConfig.DISPERSE_GOLD_TIME + GameConfig.DISPERSE_GOLD_PLAY_DURATION + GameConfig.DISPERSE_GOLD_PLAY_EXTEND * (honoraryNum - 1);
        //花石纲在活动时间内 都可以收到
        if (NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()) != null
                && NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()).getType() == eActivityType.CrossHuaShiGangActivity.getValue()) {
            return (!ActivityMgr.activityInShowTime(NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId())));
        }

        //秦始皇陵在活动时间内 都可以收到
        if (NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()) != null
                && NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()).getType() == eActivityType.Tomb.getValue()) {
            return (!ActivityMgr.activityInShowTime(NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId())));
        }
        return time > duration;
    }

    public static boolean isDisperseGoldOutSendTime(ActivityDisperseGoldInfo disperseGoldInfo, int leadTime) {
        // 距离开始送财时间间隔
        long time = (System.currentTimeMillis() - disperseGoldInfo.getBeginTime()) / 1000;
        int duration = GameConfig.DISPERSE_GOLD_TIME - leadTime;
        //花石纲在活动时间内 都可以收到
        if (NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()) != null
        && NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()).getType() == eActivityType.CrossHuaShiGangActivity.getValue()) {
            return (!ActivityMgr.activityInShowTime(NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId())));
        }

        if (NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()) != null
                && NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId()).getType() == eActivityType.Tomb.getValue()) {
            return (!ActivityMgr.activityInShowTime(NormalActivityMgr.getActivityInfo(disperseGoldInfo.getActivityId())));
        }

        return time > duration;
    }
}
